'use strict';

const log = require('@x3-cli-dev/log');

class Command {
  constructor(argv) {
    log.verbose('Command constructor', argv);
    if (!argv) {
      throw new Error('参数不能为空！');
    }
    if (!Array.isArray(argv)) {
      throw new Error('参数必须为数组！');
    }
    if (argv.length < 1) {
      throw new Error('参数列表为空！');
    }
    
    this._argv = argv;
    let runner = new Promise(() => {
      let chain = Promise.resolve();
      chain = chain.then(() => this.initArgs());
      chain = chain.then(() => this.init());
      chain = chain.then(() => this.exec());
      chain.catch((error) => {
        log.error(error.message);
      });
    });

    Object.defineProperty(this, 'runner', {
      value: runner,
    });
  }

  initArgs() {
    Object.defineProperty(this, '_cmd', {
      value: Object.freeze(this._argv[this._argv.length - 1]),
    });
    Object.defineProperty(this, '_argv', {
      value: Object.freeze(this._argv.slice(0, this._argv.length - 1)),
    });
    Object.defineProperty(this, '_options', {
      value: Object.freeze(this._cmd._options),
    });
  }

  init() {
    throw new Error('init 必须实现！');
  }

  exec() {
    throw new Error('exec 必须实现！');
  }
}

module.exports = Command;
